package com.lb.statck.controller;


import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lb.statck.common.result.R;
import com.lb.statck.common.result.Result;
import com.lb.statck.pojo.dto.LoginCode;
import com.lb.statck.pojo.dto.UserDTO;
import com.lb.statck.pojo.vo.UserVo;
import com.lb.statck.service.UserService;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;


 import java.util.HashMap;
import java.util.Map;


 @RestController

@RequestMapping("/api/user")
@Slf4j
public class UserController {
    @Value("${spring.weixin.appid}")
    private String appID;
    @Value("${spring.weixin.appsecret}")
    private String appSecret;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private WebClient webClient;

    /**
     * 获取保存用户信息
     *
     * @param user
     * @return
     */
    @GetMapping("insert")
    public Result insert(@RequestParam(value = "url") String url,@RequestParam(value = "id") int id) {
       UserVo userVo = new UserVo();
       //userVo.setId(id);
       userVo.setImageUrl(url);
      UpdateWrapper<UserVo> updateWrapper = new UpdateWrapper<>();
      updateWrapper.eq("id", id);
    // userService.
      userService.update(userVo, updateWrapper);
      Result result = new Result();
        result.setCode(0);
        return result;
    }

    @PostMapping("insert1")
    public Result insert1(@RequestBody LoginCode loginCode) {
        //Map map = new HashMap();
        //登录凭证不能为空
        if (loginCode == null) {
            // map.put("code", 0);
            //  map.put("msg", "code 不能为空");
            //  return map;
            Result result = new Result();
            result.setCode(0);
            result.setData("code为空");
            return result;
        }
        String code = loginCode.getCode();
        //小程序唯一标识   (在微信小程序管理后台获取)
        //String wxspAppid = appID;
        //小程序的 app secret (在微信小程序管理后台获取)
        //  String wxspSecret = appSecret;
        //授权（必填）
        String grant_type = "authorization_code";
        String grant_type2 = "client_credential";
        //请求参数GET
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appID + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //String url = "https://api.example.com/data";

        // 发送 GET 请求
        String response = webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class)
                .block(); // 阻塞等待响应

        // 返回响应内容
        String result = response;
        //获取会话密钥（session_key）
        JSONObject jsonResponse = new JSONObject(response);

        // 提取 session_key 和 openid
        String sessionKey = jsonResponse.getString("session_key");
        String openid = jsonResponse.getString("openid");
        QueryWrapper<UserVo> wrapper = new QueryWrapper<>();
        wrapper.eq("payopenid", openid);
        UserVo one = userService.getOne(wrapper);
        if (one == null) {
            //UpdateWrapper<UserVo> updateWrapper = new UpdateWrapper<>();
            //updateWrapper.set("payopenid", openid);
            UserVo userVo = new UserVo();
            userVo.setPhone(loginCode.getPhone());
            userVo.setPassword(loginCode.getPassword());
            userVo.setPayOpenId(openid);
            userService.saveOrUpdate(userVo);
            UserVo one1 = userService.getOne(wrapper);
            int userID=one1.getId();
            Result result1 = new Result();
            result1.setCode(0);
            result1.setMsg("注册直接登录");
            result1.setData(userID);
            return result1;
            //    Result result1 =new Result();
            //   result1.setCode(0);
            //   result1.setData("");
            //  return result;
        }
        // 打印提取的数据
        //System.out.println("Session Key: " + sessionKey);
        //System.out.println("OpenID: " + openid);
        else {
            QueryWrapper<UserVo> wrappers = new QueryWrapper<>();
            wrappers.eq("phone", loginCode.getPhone());
            wrappers.eq("password", loginCode.getPassword());
            UserVo one1 = userService.getOne(wrappers);
            if (one1 == null) {
                Result result1 = new Result();
                result1.setCode(1);
                //result1.setData("错误");
                wrapper.eq("payopenid", openid);
                UserVo one2 = userService.getOne(wrapper);
                String phone = one2.getPhone();
                result1.setData(phone);
                return result1;
            }
            else {
             //   userService.saveOrUpdate(userVo);
                UserVo one2 = userService.getOne(wrapper);
                int userID=one2.getId();
             Result result1 = new Result();
             result1.setCode(0);
             result1.setMsg("已添加");
             result1.setData(userID);
             return result1;
        }
        }

    }
    @GetMapping("/getUser")
    public Result getUser(@RequestParam(value = "userid") String userid)
    {
        QueryWrapper<UserVo> wrapper = new QueryWrapper<>();
        wrapper.eq("id", userid);
        userService.getOne(wrapper);
        Result result = new Result();
        result.setCode(0);
        result.setMsg("");
        result.setData(userService.getOne(wrapper));
        return result;
    }
    @PostMapping("/sendcode")
    public Result sendcode(@RequestBody LoginCode loginCode) {
return  null;
    }

    @PostMapping("/h5login")
   public Result loginH5(@RequestBody LoginCode loginCode, HttpServletRequest request,
                         HttpServletResponse response)
    {
        QueryWrapper<UserVo> wrappers = new QueryWrapper<>();
        wrappers.eq("phone", loginCode.getPhone());
        wrappers.eq("password", loginCode.getPassword());
        UserVo one1 = userService.getOne(wrappers);

        if (one1 == null) {
            Result result1 = new Result();
            result1.setCode(1);
            //result1.setData("错误");
           // wrapper.eq("payopenid", openid);
        //    UserVo one2 = userService.getOne(wrapper);
          //  String phone = one2.getPhone();
           // result1.setData(phone);
            return result1;
        }
        else {
            //   userService.saveOrUpdate(userVo);
        //    UserVo one2 = userService.getOne(wrapper);
          //  int userID=one2.getId();
            HttpSession session = request.getSession(true);
            session.setAttribute("user", loginCode.getPhone());
           // request.getSession().setAttribute("user", loginCode.getPhone());
            session.setMaxInactiveInterval(180);
            // 可选：设置 Cookie
            Cookie userCookie = new Cookie("user", loginCode.getPhone());
            userCookie.setMaxAge(60 * 60 * 24 * 7); // 设置Cookie的有效期为7天
            userCookie.setPath("/"); // 设置Cookie的路径为根路径
            userCookie.setDomain("localhost"); // 设置Cookie的域名
            response.addCookie(userCookie);
            Result result1 = new Result();
            result1.setCode(0);
            result1.setData(one1.getId());
            result1.setMsg("已添加");
            //result1.setData(userID);
            log.info("Session ID: {}, User set: {}", session.getId(), loginCode.getPhone());
            if (session != null) {
                log.info("Session ID: {}, User: {}", session.getId(), session.getAttribute("user"));
            } else {
                log.info("No session found");
            }
            return result1;
        }
    }
     @RequestMapping("/logout")
     public Result logout(HttpServletRequest request, HttpServletResponse response) {
         // 获取当前会话
         HttpSession session = request.getSession(false); // 不创建新的会话
         if (session != null) {
             // 清除会话中的用户信息
             session.removeAttribute("user");
             // 可选：销毁整个会话
             session.invalidate();
         }

         // 清除 Cookie 中的用户信息
         Cookie[] cookies = request.getCookies();
         if (cookies != null) {
             for (Cookie cookie : cookies) {
                 if ("user".equals(cookie.getName())) {
                     // 设置 Cookie 的最大年龄为 0，表示立即删除
                     cookie.setMaxAge(0);
                     cookie.setPath("/"); // 设置路径为根路径
                     cookie.setDomain("localhost"); // 设置域名
                     response.addCookie(cookie);
                     break;
                 }
             }
         }

         // 返回退出登录的结果
         Result result = new Result();
         result.setCode(0);
         result.setMsg("退出登录成功");
         return result;
     }
     @Transactional
     @PostMapping("register")
     public R register(@RequestBody LoginCode loginCode)
     {   loginCode.getPhone();
         loginCode.getPassword();
         UserVo userVo = new UserVo();
         userVo.setPhone(loginCode.getPhone());
         userVo.setPassword(loginCode.getPassword());

         userService.save(userVo);
         return R.ok();
     }
}
